<template>
  <div class="top">
    <div class="top-left" >更便宜！更好用的网上购物平台</div>

    <div class="top-right" style="width: 300px;height: 30px;margin-top: 30px;margin-right: -630px">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/user/person' }">我的信息</el-breadcrumb-item>
        <el-breadcrumb-item :to="{path:'/user/order'}">我的订单</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="top_middle">
      <span> 您好   {{ data.user.nickname }} </span>
      <el-button v-if="data.user===null" type="text" @click="location.href='/login'">登录/注册</el-button>

    </div>
  </div>

  <div class="product-detail">
    <div class="business_info" style="display: flex">
      <img :src="data.business.avatar" alt="店铺头像" style="width: 70px; height: 70px;">
      <div>
        <span style="font-size: 20px;color: #F06A1D">{{ data.business.shopname }} </span>
        <div class="rating">
          <el-rate
              v-model=" data.business.rate"
              disabled
              allow-half
              :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
              :max="5"
              :texts="['差', '一般', '不错', '很好', '非常好']"
              show-text
          />
        </div>
      </div>
      <div style="margin-left: 60%">
        <el-button size="large" @click="router.push('/home')">返回</el-button>
      </div>
    </div>
    <div class="dashed" style="border-top: 2px dashed var(--el-border-color);padding-bottom: 10px"></div>
    <el-row :gutter="50">
      <el-col :span="8">
        <div class="product-info">
          <h1 class="product-title">{{ data.product.title }}</h1>
          <p class="product-price">价格：￥{{ data.product.price }}</p>
          <p CLASS="product-price">发货地：{{ data.business.address }}</p>
          <p class="sell_point">{{ data.product.sellPoint }}</p>

          <div class="actions">
            <el-button type="success" class="action-button" @click="buyNow">立即购买</el-button>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <img :src="data.product.image" alt="商品图片" class="product-image"/>
      </el-col>
    </el-row>

    <el-dialog center v-model="data.byVisible" class="card" style="width: 500px" title="确认收货地址并付款">
      <el-table
          :data="data.tableData"
          highlight-current-row
          max-height="200"
          style="width: 100%"
          @current-change="handleCurrentChange"
      >
        <el-table-column type="index" width="40"/>
        <el-table-column property="name" label="收货人" width="100"/>
        <el-table-column property="phone" label="电话号" width="120"/>
        <el-table-column property="address" label="地区" width="120"/>
        <el-table-column property="addressDetail" label="详细地址" width="120"/>
        <el-table-column label="操作" width="160">
          <template #default="scope">
            <el-button type="primary">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="success" @click="byItem">确认付款</el-button>
      <el-button type="info" @click="data.byVisible=false">返回</el-button>
    </el-dialog>
    <div v-if="data.paying" class="loading-spinner"></div>
  </div>
</template>

<script setup>
import {reactive} from 'vue';
import request from "@/utils/request.js";
import {useRoute} from "vue-router";
import {ElMessage, ElTable} from "element-plus";
import router from "@/router/index.js";
import '@/assets/css/ItemDetail.css'
import {ro} from "element-plus/es/locale/index";

const data = reactive({
  product: {},
  business: {},
  byVisible: false,
  user: {},
  selectAddress: {},
  paying: false
});

//加载页面
const route = useRoute();
const load = () => {
  data.user = JSON.parse(localStorage.getItem("user_information"));
  const id = route.params.id;
  request.get("/item/selectById/" + id).then(res => {
    if (res.code === 200) {
      console.log(res.data);
      data.product = res.data;
      request.get("/business/selectById/" + res.data.businessId).then(res => {
        if (res.code === 200) {
          data.business = res.data;
        } else {
          ElMessage.error(data.msg);
        }
      });
    } else {
      ElMessage.error(data.msg);
    }
  });
};
load();

//添加购物车
const addToCart = () => {
  console.log('商品已加入购物车');
};
//购买
const buyNow = () => {
  data.byVisible = true;
  request.get("/address/selectByUserId/" + data.user.userId).then(res => {
    if (res.code === 200) {
      data.tableData = res.data
    }
  })
}
//设置地址选择
const handleCurrentChange = (currentRow) => {
  data.selectAddress = currentRow;
}
//设置产品订单号
const generateOrderNumber = (productId) => {
  const now = new Date();
  const time = now.getTime(); // 获取当前时间的毫秒数
  // 订单号格式：OD + 时间戳 + 产品ID
  return `OD${time}${data.product.id}`;
};

const byItem = () => {
  const new_order = {}
  data.byVisible = false
  new_order.orderNo = generateOrderNumber(new_order.productId);
  new_order.productId = data.product.id;
  new_order.userId = JSON.parse(localStorage.getItem("user_information")).userId;
  new_order.payPrice = data.product.price;
  new_order.count = 1;
  new_order.status = 1;
  console.log(data.selectAddress);
  new_order.addressId = data.selectAddress.addressId;
  request.post("/order/create", new_order).then(res => {
    if (res.code === 200) {
      data.paying = true
      setTimeout(() => {
      }, 1000)
      ElMessage.success("已下单，请前往订单页付款！")
    }
  })
}


</script>
<style scoped>
.loading-spinner {
  display: none;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border: 5px solid #f3f3f3;
  border-top: 5px solid #3498db;
  border-radius: 50%;
  width: 50px;
  height: 50px;
  animation: spin 2s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
